<?php

namespace app\admin\controller;

use app\models\{CopyList, Admin as model, AdminLogin, Lists, Peizhi, Ecsource, Laiyuan, Tags, Exphone, ExphoneLog, Config};
use app\validate\Admin as Validates;
use think\Validate;
use think\Db;
use think\facade\Debug;
use app\facade\Redis;
use think\facade\Log;
use think\facade\App;
use think\facade\Config as Configpz;



class Admin extends Base
{


    public function copylist()
    {
        if ($this->request->isAjax()) {
            $model = new CopyList();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->order(['id' => 'desc'])->where($where)->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['value'] = json_decode($lists['value'], true) ?? [];
                $lists['status_text'] = $lists['status'] == 1 ? '开启' : '关闭';
                $values['pbpp'] = explode(',', $lists['value']['pbpp']) ?? [];
                $lists['pbpp_list'] = '';
                if (!empty($values['pbpp'])) {
                    $pps = (new Peizhi())->where(['type' => $values['pbpp']])->column('pinpai');
                    $pps = implode(',', $pps);
                    $lists['pbpp_list'] = $pps;
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }


    public function copylist_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'status' => 'require|in:1,2',
            ], [
                'name.require' => '计划名称不能为空',
                'status.require' => '开启状态不能为空',
                'status.in' => '开启状态不正确',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $data['value']['pbpp'] = $data['value']['pbpp'] ?? [];
            $data['value']['provincelist'] = $data['value']['provincelist'] ?? [];
            $data['value']['channellist'] = $data['value']['channellist'] ?? [];
            $data['value']['pbpp'] = implode(',', $data['value']['pbpp']) ?? '';
            $data['value']['provincelist'] = implode(',', $data['value']['provincelist']) ?? '';
            $data['value']['channellist'] = implode(',', $data['value']['channellist']) ?? '';
            $data['value']['fuzhinumber'] =  0;
            $data['value'] = json_encode($data['value'], true) ?? '';
            Db::startTrans();
            try {
                // if ($data['status'] == 1) {
                //     (new CopyList())->where('status', 1)->update(['status' => 2]);
                // }
                if ($data['id'] > 0) {
                    (new CopyList())->allowfield(true)->save($data, ['id' => $data['id']]);
                } else {
                    (new CopyList())->allowfield(true)->save($data);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'msg' => '编辑成功']);
        } else {
            $id = $this->request->get('id/d', 0);
            $copy = $this->request->get('copy/d', 0);
            $row = (new CopyList())->where('id', $id)->find();
            $selects = [];
            if ($row) {
                $values = json_decode($row['value'], true) ?? [];
                $values['pbpp'] = explode(',', $values['pbpp']) ?? [];
                if (empty($values['provincelist'])) {
                    $values['provincelist'] = [];
                } else {
                    $values['provincelist'] = explode(',', $values['provincelist']) ?? [];
                }
                if (empty($values['channellist'])) {
                    $values['channellist'] = [];
                } else {
                    $values['channellist'] = explode(',', $values['channellist']) ?? [];
                }
                $values['fuzhinumber'] = (int)$values['fuzhinumber'] ?? 0;
                $row['value'] = $values;
                if ($copy == 1) {
                    $row['id'] = 0;
                    $row['name'] = $row['name'] . '副本';
                }
            }
            $pinpai = (new Peizhi())->select();
            $provincelist = (new Exphone())->whereNotNull('province')->group('province')->column('province');
            $channellist = (new Exphone())->whereNotNull('channel')->group('channel')->column('channel');
            return view('', [
                'row' => $row,
                'laiyuan' => $selects,
                'pinpai' => $pinpai,
                'provincelist' => $provincelist,
                'channellist' => $channellist
            ]);
        }
    }

    public function config()
    {
        if ($this->request->isAjax()) {
            $model = new Config();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $where[] = ['name', '<>', 'fuzhinumber'];
            $list = $model->where($where)->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                if (empty($lists['value'])) {
                    $lists['value'] = '未设置';
                } elseif ($lists['name'] == 'fuzhinumber') {
                    $lists['value'] = '请编辑查看';
                } elseif ($lists['name'] == 'leimu') {
                    $lists['value'] = '请编辑查看';
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            // $value = (new Config())->where('name', 'tags')->value('value') ?? '';
            // $value = explode(',', $value);
            // // 将数组转换为正则表达式
            // $regexp = implode('|', array_map(function ($value) {
            //     return preg_quote($value, '/'); // 转义特殊字符
            // }, $value));
            // $result = (new Exphone())
            //     ->where('yxtags', 'NOT REGEXP', $regexp)
            //     ->limit(100)
            //     ->select();
            return view(null, []);
        }
    }

    public function leimu_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'leimu' => 'require',
            ], [
                'leimu.require' => '名称不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            $category = config('config.category');
            $category[] = $data['leimu'];
            return json(['code' => 200, 'msg' => '编辑成功']);
        } else {
            return view('', []);
        }
    }


    public function config_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
            ], [
                'name.require' => '名称不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if ($data['name'] == 'fuzhinumber') {
                $data['value']['pbpp'] = $data['value']['pbpp'] ?? [];
                $data['value']['provincelist'] = $data['value']['provincelist'] ?? [];
                $data['value']['pbpp'] = implode(',', $data['value']['pbpp']) ?? '';
                $data['value']['provincelist'] = implode(',', $data['value']['provincelist']) ?? '';
                $data['value']['fuzhinumber'] = (int)$data['value']['fuzhinumber'] ?? 0;
                $data['value'] = json_encode($data['value'], true) ?? '';
            }
            if ($data['name'] == 'laiyuan' || $data['name'] == 'tags') {
                $data['value'] = implode(',', $data['value']) ?? '';
            }
            if ($data['name'] == 'drtime') {
                $data['value'][0] = (int)$data['value'][0] ?? 20;
                $data['value'][1] = (int)$data['value'][1] ?? 365;
                if ($data['value'][0] >= $data['value'][1]) {
                    return json(['code' => 1, 'msg' =>  '起始日期不能超过结束日期']);
                }
                $data['value'] = implode('-', $data['value']);
            }
            if ($data['name'] == 'leimu') {
                $data['value'] = $data['value'] ?? [];
                if (!empty($data['value1'])) {
                    $data['value'][] = $data['value1'];
                }
                $data['value'] = json_encode($data['value'], true) ?? '';
            }
            $res = (new Config())->allowfield(true)->save($data, ['name' => $data['name']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '编辑成功']);
            }
            return json(['code' => 1, 'msg' => '编辑失败']);
        } else {
            $name = $this->request->get('name/s', '');
            $row = (new Config())->where('name', $name)->find();
            $selects = [];
            if (!empty($row) && ($row['name'] == 'fuzhinumber')) {
                $values = json_decode($row['value'], true) ?? [];
                $values['pbpp'] = explode(',', $values['pbpp']) ?? [];
                $values['provincelist'] = explode(',', $values['provincelist']) ?? [];
                $values['fuzhinumber'] = (int)$values['fuzhinumber'] ?? 0;
                $row['value'] = $values;
            }
            if (!empty($row) && ($row['name'] == 'drtime')) {
                $row['value'] = explode('-', $row['value']) ?? [];
            }
            if (!empty($row) && ($row['name'] == 'leimu')) {
                $row['value'] = json_decode($row['value'], true);
            }
            if (!empty($row) && ($row['name'] == 'laiyuan')) {
                $selects = (new Exphone())->group('channel')->column('channel') ?? [];
                $selects = array_filter($selects);
                $row['value'] = explode(',', $row['value'] ?? []);
            }
            if (!empty($row) && ($row['name'] == 'tags')) {
                $selects = (new Exphone())->group('yxtags')->column('yxtags') ?? [];
                $selects = array_filter($selects) ?? [];
                $selects = implode(',', $selects);
                $selects = explode(',', $selects) ?? [];
                $selects = array_unique($selects) ?? [];
                $row['value'] = explode(',', $row['value'] ?? []);
            }
            $pinpai = (new Peizhi())->where('status', 1)->select();
            $provincelist = (new Exphone())->whereNotNull('province')->group('province')->column('province');
            return view('', [
                'row' => $row,
                'laiyuan' => $selects,
                'pinpai' => $pinpai,
                'provincelist' => $provincelist,
            ]);
        }
    }

    public function excall()
    {
        if ($this->request->isAjax()) {
            $model = new Exphone();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['phone|channel', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['channel'])) {
                $where[] = ['channel', '=', $post['channel']];
            }
            if (!empty($post['yxtags'])) {
                $value = explode(',', $post['yxtags']);
                // 将数组转换为正则表达式
                $regexp = implode('|', array_map(function ($value) {
                    return preg_quote($value, '/'); // 转义特殊字符
                }, $value));
                $where[]   = ['yxtags', 'REGEXP', $regexp];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $lypinpai = (new Peizhi())->where(['type' => $row['type']])->column('pinpai') ?? [];
                $row['lypinpai'] = implode(',', $lypinpai);
                $lympinpai = (new Peizhi())->where(['type' => $row['typem']])->column('pinpai') ?? [];
                $row['nnpinpai'] = implode(',', $lympinpai);
                $types = explode(',', $row['types']);
                $pinpai = (new Peizhi())->where(['type' => $types])->column('pinpai') ?? [];
                $row['pinpai'] = implode(',', $pinpai);
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $laiyuan = (new Exphone())->group('channel')->column('channel') ?? [];
            $laiyuan = array_filter($laiyuan);
            $yxtags = (new Exphone())->group('yxtags')->column('yxtags') ?? [];
            $yxtags = array_filter($yxtags) ?? [];
            $yxtags = implode(',', $yxtags);
            $yxtags = explode(',', $yxtags) ?? [];
            $yxtags = array_unique($yxtags) ?? [];
            return view(null, ['laiyuan' => $laiyuan, 'yxtags' => $yxtags]);
        }
    }

    public function exphonelog()
    {
        if ($this->request->isAjax()) {
            $model = (new ExphoneLog())->alias('el')->leftJoin('exphone e', 'e.id = el.exId');
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['el.isrepeat', '=', 1];
            if (!empty($post['title'])) {
                $where[] = ['e.phone|e.channel', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['typem'])) {
                $where[] = ['el.typem', '=', $post['typem']];
            }
            if (!empty($post['created'])) {
                $where[] = ['el.date', '=', $post['created']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->field('e.phone,e.createTime,e.yxtags,e.typem as typeml,e.address,e.channel,el.typem,el.date,el.typem')->order("el.id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $lympinpai = (new Peizhi())->where(['type' => $row['typeml']])->column('pinpai') ?? [];
                $row['nnpinpai'] = implode(',', $lympinpai);
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function tongji()
    {
        if ($this->request->isAjax()) {
            $model = new Lists();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['li.videoid', '>', 0];
            $where[] = ['pe.status', '=', 1];
            if (!empty($post['type'])) {
                $where[] = ['li.type', '=', $post['type']];
            }
            if (!empty($post['videoid'])) {
                $where[] = ['li.videoid', '=', trim($post['videoid'])];
            }
            if (!empty($post['adv_id'])) {
                $where[] = ['li.adv_id', '=', trim($post['adv_id'])];
            }
            if (!empty($post['created'])) {
                $times = explode('~', $post['created']);
                if (count($times) != 2) {
                    $where[] = ['li.id', '=', 0];
                } else {
                    $startime = trim($times[0]) ?? '';
                    $endtime = trim($times[1]) ?? '';
                    $where[] = ['li.created', '>= time', $startime . ' 00:00:00'];
                    $where[] = ['li.created', '<= time', $endtime . ' 23:59:59'];
                }
            }
            $list = $model->alias('li')->leftJoin('peizhi pe', 'pe.type = li.type')->group('li.videoid,li.type');
            $count = $model->alias('li')->leftJoin('peizhi pe', 'pe.type = li.type')->group('li.videoid,li.type')->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $list->where($where)->limit($limit)->page($page)->column('li.videoid,li.type,li.adv_id,pe.pinpai');
            foreach ($list as &$row) {
                //$row['pinpai'] = (new Peizhi())->where('type', $row['type'])->value('pinpai') ?? '';
                $row['yunying'] = (new Laiyuan())->where('ly', $row['adv_id'])->value('yyname') ?? '';
                $number = $model->where(['type' => $row['type'], 'videoid' => $row['videoid']]);
                $youxiao = $model->where(['type' => $row['type'], 'videoid' => $row['videoid'], 'youxiao' => 1]);
                $wuxiao = $model->where(['type' => $row['type'], 'videoid' => $row['videoid'], 'youxiao' => 2]);
                if (!empty($startime) && !empty($endtime)) {
                    $number = $number->where('created', '>= time', $startime . ' 00:00:00')->where('created', '<= time', $endtime . ' 23:59:59');
                    $youxiao = $youxiao->where('created', '>= time', $startime . ' 00:00:00')->where('created', '<= time', $endtime . ' 23:59:59');
                    $wuxiao = $wuxiao->where('created', '>= time', $startime . ' 00:00:00')->where('created', '<= time', $endtime . ' 23:59:59');
                }
                $number = $number->count();
                $youxiao = $youxiao->count();
                $wuxiao = $wuxiao->count();
                $row['number'] = $number;
                $row['youxiao'] = $youxiao;
                $row['wuxiao'] = $wuxiao;
                if ($row['number'] <= 0) {
                    $row['youxiaolv'] = 0;
                } else {
                    $row['youxiaolv'] = floor($row['youxiao'] * 100 / $row['number']) . '%';
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $pinpai = (new Peizhi())->where('status', 1)->select();
            $laiyuan = (new Laiyuan())->select();
            return view(null, ['pinpai' => $pinpai, 'laiyuan' => $laiyuan]);
        }
    }

    public function pinpai()
    {
        if ($this->request->isAjax()) {
            $model = new Peizhi();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            if (!empty($post['title'])) {
                $where[] = ['pinpai', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            } else {
                $where[] = ['status', '=', 1];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            $category = (new Config())->where('name', 'leimu')->value('value') ?? '';
            $category = json_decode($category, true) ?? [];
            foreach ($list as $row) {
                $row['pbpp'] = explode(',', $row['pbpp']) ?? [];
                if (empty($row['pbpp'])) {
                    $row['pbpinpai'] = '';
                } else {
                    $pbpinpais = (new Peizhi())->where(['type' => $row['pbpp']])->column('pinpai') ?? [];
                    $row['pbpinpai'] =  implode(',', $pbpinpais);
                }
                if (empty($row['wzly'])) {
                    $row['wzly_name'] = '未设置默认';
                } else {
                    $row['wzly_name'] = (new Ecsource())->where(['type' => $row['type'], 'ecid' => $row['wzly']])->value('ecname') ?? '';
                }
                if (empty($row['type'])) {
                    $rm = $model->where('id', $row['id'])->update(['type' => $row['id']]);
                    if ($rm) {
                        $row['type'] = $row['id'];
                    }
                }
                $row['url'] = 'https://' . env('app.api_url') . '/other/list?type=' . $row['type'];
                $row['url2'] = 'https://' . env('app.api_url') . '/other/list_ks?type=' . $row['type'];
                if (empty($row['type'])) {
                    $row['url'] = '生成失败,请刷新页面';
                    $row['url2'] = '生成失败,请刷新页面';
                }
                if (empty($row['category'])) {
                    $row['category_name'] = '未设置类目';
                } else {
                    $row['category_name'] = $category[$row['category']] ?? '';
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $other = new \app\admin\controller\Lista();
            App::invokeMethod([$other, 'laiyuan']);
            App::invokeMethod([$other, 'tags']);
            return view(null, []);
        }
    }

    public function pinpai_edit2()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'kags' => 'require|in:1,2',
                'youxiao' => 'require|egt:0',
                'wuxiao' => 'require|egt:0',
                'times' => 'require|egt:1',
                'startime' => 'require|egt:1|elt:24',
                'endtime' => 'require|egt:1|elt:24',
            ], [
                'pinpai.require' => '开关不能为空',
                'pinpai.in' => '开关参数不正确',
                'youxiao.require' => '日有效不能为空',
                'youxiao.egt' => '日有效必须大于等于0',
                'wuxiao.require' => '日无效不能为空',
                'wuxiao.egt' => '日无效必须大于等于0',
                'times.require' => '间隔时间不能为空',
                'times.egt' => '间隔时间必须大于等于1',
                'startime.require' => '开始时间不能为空',
                'startime.egt' => '开始时间必须大于等于1',
                'startime.elt' => '开始时间必须大于等于24',
                'endtime.require' => '结束时间不能为空',
                'endtime.egt' => '结束时间必须大于等于1',
                'endtime.elt' => '结束时间必须大于等于24',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            if ($data['startime'] > $data['endtime']) {
                return json(['code' => 1, 'msg' => '开始时间不能大于结束时间']);
            }
            if (empty($data['id'])) {
                return json(['code' => 1, 'msg' => '操作失败,请重试']);
            }
            $data['pbpp'] = $data['pbpp'] ?? [];
            $data['pbpp'] = implode(',', $data['pbpp']) ?? '';
            $data['provincelist'] = $data['provincelist'] ?? [];
            $data['provincelist'] = implode(',', $data['provincelist']) ?? '';
            $datas = [
                'kags' => (int)$data['kags'],
                'pbpp' => $data['pbpp'],
                'provincelist' => $data['provincelist'],
                'youxiao' =>  (int)$data['youxiao'],
                'wuxiao' => (int) $data['wuxiao'],
                'times' =>  (int)$data['times'],
                'startime' =>  (int)$data['startime'],
                'endtime' =>  (int)$data['endtime'],
                'datebefore' =>  (int)$data['datebefore'] ?? 0,
                'dateafter' =>  (int)$data['dateafter'] ?? 0,
                'daterangestar' => trim($data['daterangestar'] ?? ''),
                'daterangeend' => trim($data['daterangeend'] ?? ''),
            ];
            if ((!empty($datas['datebefore']) || !empty($datas['dateafter'])) && $datas['datebefore'] >= $datas['dateafter']) {
                return json(['code' => 1, 'msg' => '操作失败,资源日期起始日期不能大于等于结束日期']);
            }
            if ((!empty($datas['daterangestar']) || !empty($datas['daterangeend'])) && $datas['daterangestar'] >= $datas['daterangeend']) {
                return json(['code' => 1, 'msg' => '操作失败,资源导入日期不能大于等于结束日期']);
            }
            $res = (new Peizhi())->allowfield(true)->save($datas, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败,请重试']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Peizhi())->where('id', $id)->find();
            if (!empty($row['pbpp'])) {
                $row['pbpp'] = explode(',', $row['pbpp']) ?? [];
            }
            if (!empty($row['provincelist'])) {
                $row['provincelist'] = explode(',', $row['provincelist']) ?? [];
            }
            $pinpai = (new Peizhi())->where('id', '<>', $id)->select();
            $provincelist = (new Exphone())->whereNotNull('province')->group('province')->column('province');
            return view('', ['row' => $row, 'pinpai' => $pinpai, 'provincelist' => $provincelist]);
        }
    }

    public function pinpai_edit3()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'isexphone' => 'require|in:1,2',
                // 'exnumber' => 'require|egt:0',
            ], [
                'isexphone.require' => '开关不能为空',
                'isexphone.in' => '开关参数不正确',
                // 'exnumber.require' => '日复制数量不能为空',
                // 'exnumber.egt' => '日复制数量必须大于等于0'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            if (empty($data['id'])) {
                return json(['code' => 1, 'msg' => '操作失败,请重试']);
            }
            $data['ispbpp'] = $data['ispbpp'] ?? [];
            $data['ispbpp'] = implode(',', $data['ispbpp']) ?? '';
            $datas = [
                'isexphone' => (int)$data['isexphone'],
                'ispbpp' => $data['ispbpp'],
                'exnumber' => $data['exnumber'] ?? 0,
            ];
            $res = (new Peizhi())->allowfield(true)->save($datas, ['id' => $data['id']]);
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败,请重试']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Peizhi())->where('id', $id)->find();
            if (!empty($row['ispbpp'])) {
                $row['ispbpp'] = explode(',', $row['ispbpp']) ?? [];
            }
            $pinpai = (new Peizhi())->where('id', '<>', $id)->select();
            return view('', ['row' => $row, 'pinpai' => $pinpai]);
        }
    }

    public function pinpai_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'pinpai' => 'require',
                'cid' => 'require',
                'appId' => 'require',
                'appSecret' => 'require',
            ], [
                'pinpai.require' => '品牌来源不能为空',
                'cid.require' => 'EC-cid不能为空',
                'appId.require' => 'EC-appID来源不能为空',
                'appSecret.require' => 'EC-appSecret来源不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            // if (empty($data['id'])) {
            //     return json(['code' => 1, 'msg' => '操作失败,请重试']);
            // }
            if ($data['id'] > 0) {
                $res = (new Peizhi())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new Peizhi())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败,请重试']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Peizhi())->where('id', $id)->find();
            $eclaiyuan = (new Ecsource())->where(['type' => $row['type']])->select() ?? [];
            $category = (new Config())->where('name', 'leimu')->value('value') ?? '';
            $category = json_decode($category, true) ?? [];
            return view('', ['row' => $row, 'eclaiyuan' => $eclaiyuan, 'category' => $category]);
        }
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new model();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['id', '<>', $this->request->admin['id']];
            if (!empty($post['title'])) {
                $where[] = ['nickname|username', 'like', '%' . $post['title'] . '%'];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $row) {
                $row['groups'] = array_filter(explode(',', $row['groups'])) ?? [];
                $row['groups_name'] = '';
                if (count($row['groups']) > 0) {
                    $pz = (new Peizhi())->where(['type' => $row['groups']])->select();
                    foreach ($pz as $pzs) {
                        $row['groups_name'] .= $pzs['pinpai'] . ' ';
                    }
                }
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }

    public function input()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('data');
            $validate = new Validates();
            if (!$validate->scene('add')->check($data) && empty($data['id'])) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            if (!$validate->scene('edit')->check($data) && !empty($data['id'])) {
                return json(['code' => 1, 'msg' => $validate->getError()]);
            }
            $haveadmin = (new model())->where('username', $data['username'])->find();
            if (!empty($haveadmin) && $haveadmin['id'] != $data['id']) {
                return json(['code' => 1, 'msg' => '账号名称已被使用']);
            }
            $data['role'] = implode(',', $data['role'] ?? []);
            $data['groups'] = implode(',', $data['groups'] ?? []);
            if (isset($data['password']) && $data['password']) {
                $data['passwordword'] = $data['password'];
                $entry = $this->get_rand_str();
                $data['entry'] = $entry;
                $data['password'] = md5(md5($data['password']) . md5($entry));
            } else {
                unset($data['password']);
            }
            if ($data['id'] > 0) {
                $res = (new model())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = (new model())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败,请重试']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new model())->where('id', $id)->find();
            if (!empty($row)) {
                $row['role'] = array_filter(explode(',', $row['role']));
                $row['groups'] = array_filter(explode(',', $row['groups']));
            } else {
                $data['role'] = [];
                $data['groups'] = [];
            }
            $pinpai = (new Peizhi())->field('id,type,pinpai')->select();
            return view('', [
                'pinpai' => $pinpai,
                'data' => $row,
                'role' => $this->request->admin['role']
            ]);
        }
    }

    public function del()
    {
        $admin_id =  $this->request->get('id');
        $admin = (new model())->where('id', $admin_id)->find();
        if ($admin['is_default'] == 1) {
            return json(['status' => 1, 'msg' => '超级管理员不允许删除']);
        }
        $res = (new model())->where('id', $admin_id)->delete();
        if ($res) {
            return json(['code' => 200, 'msg' => '删除成功']);
        }
        return json(['code' => 1, 'msg' => '操作失败']);
    }

    public function login_log()
    {
        if ($this->request->isAjax()) {
            $model = new AdminLogin();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['uid', '=', $this->request->admin['id']];
            if (!empty($post['title'])) {
                $where[] = ['username', 'like', '%' . $post['title'] . '%'];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id asc")->limit($limit)->page($page)->select();
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view('', []);
        }
    }
}
